package com.leiyuan.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leiyuan.learning.feignclient.ContentServiceClient;
import com.leiyuan.learning.mapper.ElChooseCourseMapper;
import com.leiyuan.learning.mapper.ElCourseTablesMapper;
import com.leiyuan.learning.model.dto.ElChooseCourseDto;
import com.leiyuan.learning.model.dto.ElCourseTablesDto;
import com.leiyuan.learning.model.dto.MyCourseTableParams;
import com.leiyuan.learning.model.po.ElChooseCourse;
import com.leiyuan.learning.model.po.ElCourseTables;
import com.leiyuan.learning.service.MyCourseTablesService;
import com.leiyuan.model.PageResult;
import com.leiyuan.po.CoursePublish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author leiyuan
 * @version 1.0
 * @description TODO
 */
@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {

    @Autowired
    ContentServiceClient contentServiceClient;

    //选课记录表的mapper
    @Autowired
    ElChooseCourseMapper chooseCourseMapper;

    //我的课程表mapper
    @Autowired
    ElCourseTablesMapper courseTablesMapper;

    //添加选课
    @Override
    public ElChooseCourseDto addChooseCourse(String userId, Long courseId) {

        //调用内容管理服务查询课程信息
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        //收费规则
        String charge = coursepublish.getCharge();
        ElChooseCourse elChooseCourse = null;
        if ("201000".equals(charge)) {//免费课程
            //添加免费课程
            elChooseCourse = addFreeCoruse(userId, coursepublish);

        } else {
            //收费课程，只能添加到选课记录表
            elChooseCourse = addChargeCoruse(userId, coursepublish);
        }

        //获取用户对该课程的学习资格
        ElCourseTablesDto xcCourseTablesDto = getLearningStatus(userId, courseId);
        //学习资格
        String learnStatus = xcCourseTablesDto.getLearnStatus();

        //构造返回对象
        ElChooseCourseDto xcChooseCourseDto = new ElChooseCourseDto();
        BeanUtils.copyProperties(elChooseCourse, xcChooseCourseDto);
        xcChooseCourseDto.setLearnStatus(learnStatus);//学习资格

        return xcChooseCourseDto;
    }

    //学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
    @Override
    public ElCourseTablesDto getLearningStatus(String userId, Long courseId) {
        //从哪里查询数据进行判断学习资格
        ElCourseTables elCourseTables = getXcCourseTables(userId, courseId);
        ElCourseTablesDto xcCourseTablesDto = new ElCourseTablesDto();
        if (elCourseTables == null) {
            xcCourseTablesDto.setLearnStatus("702002");//没有学习资格
            return xcCourseTablesDto;
        }
        BeanUtils.copyProperties(elCourseTables, xcCourseTablesDto);
        //判断课程是否过期
        LocalDateTime validtimeEnd = elCourseTables.getValidtimeEnd();
        if (LocalDateTime.now().isAfter(validtimeEnd)) {//说明课程已过期
            xcCourseTablesDto.setLearnStatus("702003");//已经过期
            return xcCourseTablesDto;
        }
        //正常学习
        xcCourseTablesDto.setLearnStatus("702001");//正常学习
        return xcCourseTablesDto;
    }

    @Override
    public PageResult<ElCourseTables> mycoursetables(MyCourseTableParams params) {
        //用户id
        String userId = params.getUserId();
        //当前页码
        int pageNo = params.getPage();
        //每页记录数
        int size = params.getSize();

        Page<ElCourseTables> courseTablesPage = new Page<>(pageNo, size);
        LambdaQueryWrapper<ElCourseTables> lambdaQueryWrapper = new LambdaQueryWrapper<ElCourseTables>().eq(ElCourseTables::getUserId, userId);

        //查询数据
        Page<ElCourseTables> result = courseTablesMapper.selectPage(courseTablesPage, lambdaQueryWrapper);

        //数据列表
        List<ElCourseTables> records = result.getRecords();
        //总记录数
        long total = result.getTotal();

        //List<T> items, long counts, long page, long pageSize
        PageResult pageResult = new PageResult(records, total, pageNo, size);

        return pageResult;
    }

    //添加免费课程,免费课程加入选课记录表、我的课程表
    @Transactional
    public ElChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
        //课程id
        Long courseId = coursepublish.getId();
        //校验该课程是否添加到了选课记录表，如果已添加则直接返回
        LambdaQueryWrapper<ElChooseCourse> queryWrapper = new LambdaQueryWrapper<ElChooseCourse>().eq(ElChooseCourse::getUserId, userId)
                .eq(ElChooseCourse::getCourseId, courseId)
                .eq(ElChooseCourse::getOrderType, "700001")//免费课程
                .eq(ElChooseCourse::getStatus, "701001");
        List<ElChooseCourse> elChooseCours = chooseCourseMapper.selectList(queryWrapper);
        if (elChooseCours != null && elChooseCours.size() > 0) {
            return elChooseCours.get(0);
        }

        //向选课记录表添加记录
        ElChooseCourse chooseCourse = new ElChooseCourse();
        chooseCourse.setCourseId(courseId);
        chooseCourse.setCourseName(coursepublish.getName());
        chooseCourse.setUserId(userId);
        chooseCourse.setCompanyId(coursepublish.getCompanyId());
        chooseCourse.setOrderType("700001");//免费课程
        chooseCourse.setCreateDate(LocalDateTime.now());
        chooseCourse.setCoursePrice(0f);//免费课程的价格为0
        chooseCourse.setValidDays(coursepublish.getValidDays());//有效期(天)
        chooseCourse.setStatus("701001");//选课成功
        chooseCourse.setValidtimeStart(LocalDateTime.now());
        chooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));//截止日期
        chooseCourseMapper.insert(chooseCourse);

        //向我的课程表添加记录
        ElCourseTables courseTables = addCourseTables(chooseCourse);


        return chooseCourse;
    }

    //添加收费课程
    @Transactional
    public ElChooseCourse addChargeCoruse(String userId, CoursePublish coursepublish) {
        //课程id
        Long courseId = coursepublish.getId();
        //校验该课程是否添加到了选课记录表，如果已添加则直接返回
        LambdaQueryWrapper<ElChooseCourse> queryWrapper = new LambdaQueryWrapper<ElChooseCourse>().eq(ElChooseCourse::getUserId, userId)
                .eq(ElChooseCourse::getCourseId, courseId)
                .eq(ElChooseCourse::getOrderType, "700002")//收费课程
                .eq(ElChooseCourse::getStatus, "701002");//待支付
        List<ElChooseCourse> elChooseCours = chooseCourseMapper.selectList(queryWrapper);
        if (elChooseCours != null && elChooseCours.size() > 0) {
            return elChooseCours.get(0);
        }

        //向选课记录添加记录
        ElChooseCourse chooseCourse = new ElChooseCourse();
        chooseCourse.setCourseId(courseId);
        chooseCourse.setCourseName(coursepublish.getName());
        chooseCourse.setUserId(userId);
        chooseCourse.setCompanyId(coursepublish.getCompanyId());
        chooseCourse.setOrderType("700002");//收费课程
        chooseCourse.setCreateDate(LocalDateTime.now());
        chooseCourse.setCoursePrice(coursepublish.getPrice());
        chooseCourse.setValidDays(coursepublish.getValidDays());//有效期(天)
        chooseCourse.setStatus("701002");//待支付
        chooseCourse.setValidtimeStart(LocalDateTime.now());
        chooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));//截止日期
        chooseCourseMapper.insert(chooseCourse);


        return chooseCourse;
    }

    /**
     * @param elChooseCourse 选课记录
     * @return com.leiyuan.learning.model.po.ElChooseCourse
     * @description 添加到我的课程表
     * @author leiyuan
     */
    @Transactional
    public ElCourseTables addCourseTables(ElChooseCourse elChooseCourse) {
        //校验该课程在我的课程表中是否存在
        //课程id
        Long courseId = elChooseCourse.getCourseId();
        //用户id
        String userId = elChooseCourse.getUserId();
        ElCourseTables elCourseTables = getXcCourseTables(userId, courseId);
        if (elCourseTables != null) {
            return elCourseTables;
        }
        //向我的课程表添加记录
        ElCourseTables courseTables = new ElCourseTables();
        //选课记录id
        Long xcChooseCourseId = elChooseCourse.getId();
        courseTables.setChooseCourseId(xcChooseCourseId);
        courseTables.setUserId(elChooseCourse.getUserId());
        courseTables.setCourseId(elChooseCourse.getCourseId());
        courseTables.setCompanyId(elChooseCourse.getCompanyId());
        courseTables.setCourseName(elChooseCourse.getCourseName());
        courseTables.setCreateDate(LocalDateTime.now());
        courseTables.setValidtimeStart(elChooseCourse.getValidtimeStart());
        courseTables.setValidtimeEnd(elChooseCourse.getValidtimeEnd());
        courseTables.setCourseType(elChooseCourse.getOrderType());
        courseTablesMapper.insert(courseTables);
        return courseTables;

    }

    @Override
    public boolean saveChooseCourseSuccess(String chooseCourseId) {
        return false;
    }

    /**
     * 根据课程和用户查询我的课程表中某一门课程
     *
     * @param userId
     * @param courseId
     * @return com.leiyuan.learning.model.po.ElCourseTables
     * @author leiyuan
     */
    public ElCourseTables getXcCourseTables(String userId, Long courseId) {


        LambdaQueryWrapper<ElCourseTables> queryWrapper = new LambdaQueryWrapper<ElCourseTables>().eq(ElCourseTables::getCourseId, courseId)
                .eq(ElCourseTables::getUserId, userId);
        ElCourseTables courseTables = courseTablesMapper.selectOne(queryWrapper);
        return courseTables;

    }


}
